/**
 * 通用数据加载工具
 * 解决页面数据加载问题
 */

import { ElMessage } from 'element-plus'

/**
 * 通用数据加载函数
 * @param {Function} loadFunction - 实际的数据加载函数
 * @param {Object} options - 配置选项
 * @returns {Promise} 加载结果
 */
export async function loadDataWithRetry(loadFunction, options = {}) {
  const {
    maxRetries = 3,
    retryDelay = 1000,
    showLoading = true,
    showError = true
  } = options

  let lastError = null

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      if (showLoading && attempt === 1) {
        ElMessage.info('正在加载数据...')
      }

      const result = await loadFunction()
      
      if (showLoading && attempt === 1) {
        ElMessage.success('数据加载成功')
      }
      
      return result
    } catch (error) {
      lastError = error
      console.error(`数据加载失败 (第${attempt}次尝试):`, error)
      
      if (attempt < maxRetries) {
        if (showError) {
          ElMessage.warning(`数据加载失败，${retryDelay/1000}秒后重试...`)
        }
        await new Promise(resolve => setTimeout(resolve, retryDelay))
      }
    }
  }

  if (showError) {
    ElMessage.error(`数据加载失败，已重试${maxRetries}次`)
  }
  
  throw lastError
}

/**
 * 模拟API请求
 * @param {number} delay - 延迟时间(毫秒)
 * @param {any} data - 返回的数据
 * @returns {Promise} 模拟的API响应
 */
export function mockApiRequest(delay = 1000, data = null) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // 模拟随机失败 - 降低失败率
      if (Math.random() < 0.05) {
        reject(new Error('模拟网络错误'))
      } else {
        resolve(data)
      }
    }, delay)
  })
}

/**
 * 创建表格数据加载器
 * @param {Array} mockData - 模拟数据
 * @param {Object} options - 配置选项
 * @returns {Object} 包含加载状态和数据的对象
 */
export function createTableDataLoader(mockData = [], options = {}) {
  const {
    loadingDelay = 800,
    enableRetry = true,
    showMessages = false
  } = options

  const state = {
    loading: false,
    data: [],
    error: null,
    total: 0
  }

  const loadData = async () => {
    state.loading = true
    state.error = null

    try {
      if (enableRetry) {
        const result = await loadDataWithRetry(
          () => mockApiRequest(loadingDelay, mockData),
          { showLoading: showMessages, showError: showMessages }
        )
        state.data = result || mockData
      } else {
        const result = await mockApiRequest(loadingDelay, mockData)
        state.data = result || mockData
      }

      state.total = state.data.length
      
      if (showMessages) {
        ElMessage.success(`成功加载 ${state.data.length} 条数据`)
      }
    } catch (error) {
      state.error = error.message
      state.data = []
      state.total = 0
      if (showMessages) {
        ElMessage.error(`数据加载失败: ${error.message}`)
      }
    } finally {
      state.loading = false
    }
  }

  return {
    state,
    loadData
  }
}

/**
 * 检查数据加载状态
 * @param {Object} state - 数据状态对象
 * @returns {Object} 状态信息
 */
export function checkDataLoadingState(state) {
  const issues = []

  if (!state) {
    issues.push('状态对象未定义')
    return { hasIssues: true, issues }
  }

  if (state.loading === undefined) {
    issues.push('缺少 loading 状态')
  }

  if (state.data === undefined) {
    issues.push('缺少 data 属性')
  }

  if (state.error === undefined) {
    issues.push('缺少 error 属性')
  }

  if (state.total === undefined) {
    issues.push('缺少 total 属性')
  }

  return {
    hasIssues: issues.length > 0,
    issues
  }
}

/**
 * 调试数据加载问题
 * @param {string} componentName - 组件名称
 * @param {Object} state - 数据状态
 */
export function debugDataLoading(componentName, state) {
  console.group(`🔍 数据加载调试 - ${componentName}`)
  
  const stateCheck = checkDataLoadingState(state)
  
  if (stateCheck.hasIssues) {
    console.error('❌ 状态对象问题:', stateCheck.issues)
  } else {
    console.log('✅ 状态对象正常')
  }

  console.log('📊 当前状态:', {
    loading: state?.loading,
    dataLength: state?.data?.length,
    total: state?.total,
    error: state?.error
  })

  if (state?.data && state.data.length > 0) {
    console.log('📋 数据示例:', state.data[0])
  }

  console.groupEnd()
}

/**
 * 改进的数据加载函数 - 专门用于列表组件
 * @param {Object} state - 状态对象
 * @param {Function} loadFunction - 加载函数
 * @param {Object} options - 选项
 */
export async function loadListData(state, loadFunction, options = {}) {
  const {
    showLoading = false,
    showError = true,
    retryCount = 2
  } = options

  if (!state) {
    console.error('状态对象未定义')
    return
  }

  state.loading = true
  state.error = null

  try {
    const result = await loadDataWithRetry(
      loadFunction,
      {
        maxRetries: retryCount,
        retryDelay: 1000,
        showLoading,
        showError
      }
    )
    
    if (result && Array.isArray(result)) {
      state.data = result
      state.total = result.length
    } else if (result && typeof result === 'object' && result.data) {
      state.data = result.data
      state.total = result.total || result.data.length
    } else {
      state.data = []
      state.total = 0
    }
  } catch (error) {
    state.error = error.message
    state.data = []
    state.total = 0
    if (showError) {
      ElMessage.error(`数据加载失败: ${error.message}`)
    }
  } finally {
    state.loading = false
  }
}

export default {
  loadDataWithRetry,
  mockApiRequest,
  createTableDataLoader,
  checkDataLoadingState,
  debugDataLoading,
  loadListData
} 